<script setup>
import { ref, computed, watch, reactive } from 'vue'
import router from "@/router/router.js"
import { debounce } from 'lodash-es'
import { message } from 'ant-design-vue'
import { EyeTwoTone, EyeInvisibleOutlined, CheckCircleTwoTone } from '@ant-design/icons-vue'
import { getStuInfo } from "@/api/stu.js";
import { userLogin } from "@/api/user.js";
import rectangleBlue from '@/assets/rectangleBlue.png'
import { userUserStore } from "@/stores/index.js";
import {getCompanyInfo} from "@/api/company.js";

const userStore = userUserStore()
const form = ref()
const isLoading = ref(false)

const formModel = ref({
  phone: '',
  password: '',
  role: 'student'
})
const validatepsd = async (_rules, value) => {
  if (value === '') {
    return Promise.reject('请输入密码')
  } else {
    return Promise.resolve();
  }
}

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'change' },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'change'
    }
  ],
  psd: [
    { required: true, validator: validatepsd, trigger: 'change' },
    {
      pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>_]).{8,20}$/,
      message: '密码必须满足下面的五个条件',
      trigger: 'change'
    }
  ],
}

// 头部样式
const headStyle = {
  textAlign: 'center',
  fontSize: '22px',
  color: 'rgb(10, 124, 142)',
  margin: '20px'
}

const goToRegister = () => {
  router.push('/register')
}
const onSubmit = async () => {
  isLoading.value = true
  localStorage.clear ()
  const resLogin = await userLogin({
    phoneNum: formModel.value.phone,
    password: formModel.value.password,
    role: formModel.value.role
  });
  if (resLogin.data.code === 200) {
    userStore.setToken(resLogin.data.data);
    message.success('登录成功');
    try {
      if(formModel.value.role === 'company'){
        const resUserInfo = await getCompanyInfo();
        userStore.setUserInfo(resUserInfo.data.data);
        router.push('/jobinfo');
      }else if(formModel.value.role === 'student'){
        const resUserInfo = await getStuInfo();
        userStore.setUserInfo(resUserInfo.data.data);
        router.push('/jobinfo');
      }
    } catch (err) {
      console.log(err.data)
    }
    router.push('/')
  } else {
    message.error(resLogin.data.message);
  }
  isLoading.value = false
}

const handleFinishFailed = errors => {
  console.log(errors);
};
const handleValidate = (...args) => {
  console.log(args);
};

// 校验条件
const hasUppercase = computed(() => /[A-Z]/.test(formModel.value.password))
const hasLowercase = computed(() => /[a-z]/.test(formModel.value.password))
const hasNumber = computed(() => /\d/.test(formModel.value.password))
const hasSpecialChar = computed(() => /[!@#$%^&*(),.?":{}|<>_]/.test(formModel.value.password))
const hasLength = computed(() => formModel.value.password.length >= 8 && formModel.value.password.length <= 20)

const passwordValidation = computed(() => ({
  length: hasLength.value,
  uppercase: hasUppercase.value,
  lowercase: hasLowercase.value,
  number: hasNumber.value,
  specialChar: hasSpecialChar.value
}))

// 判断密码是否满足所有条件
const isPasswordValid = computed(() => {
  return Object.values(passwordValidation.value).every(val => val)
})

const validatePasswordDebounced = debounce(() => {
  // 触发校验逻辑或更新UI
}, 300)

watch(() => formModel.value.password, validatePasswordDebounced)
</script>

<template>
  <a-card class="psd-form-wrapper" :head-style="headStyle"
          v-loading.fullscreen.lock="isLoading"
          element-loading-text="正在登录..."
          element-loading-background="transparent">
    <div class="title-style">
      <a-image height="30px" width="10px" :src="rectangleBlue" :preview="false"></a-image>
      <span>使用密码登录</span>
    </div>
    <a-form ref="form" :model="formModel" :rules="rules" @validate="handleValidate" @finishFailed="handleFinishFailed">
      <a-form-item>
        <a-radio-group v-model:value="formModel.role" button-style="solid" class="status">
          <a-radio-button value="student" class="status-button">我是学生</a-radio-button>
          <a-radio-button value="company" class="status-button">我是企业</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="" name="phone">`
        <a-input v-model:value="formModel.phone" placeholder="请输入手机号" style="height: 45px;" />
      </a-form-item>
      <a-form-item label="" name="password">
        <a-input-password v-model:value="formModel.password" placeholder="请输入密码" style="height: 45px" />
        <template #iconRender="v">
          <EyeTwoTone v-if="v"></EyeTwoTone>
          <EyeInvisibleOutlined v-else></EyeInvisibleOutlined>
        </template>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" class="login-button" @click="onSubmit">确认</a-button>
      </a-form-item>
    </a-form>
    <div class="additional-options">
      <a @click="goToRegister">回到注册页面</a>
    </div>

  </a-card>
</template>

<style scoped>
.login-button {
  height: 40px;
  width: 100%;
}

.psd-form-wrapper {
  width: 400px;
  height: 500px;
  margin-right: 15%;
}

.status {
  width: 100%;
  display: flex;
  background-color: white;
}

.status-button {
  background-color: white;
  width: 50%;
  height: 45px;
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
  margin: 0 auto;
  /* 水平居中 */
  font-size: 16px;
}

.additional-options {
  text-align: center;
  margin-top: 12px;

  >a {
    color: #1890ff;
    font-size: 12px;
  }
}

.title-style {
  display: flex;
  margin-top: 70px;
  text-align: left;
  font-size: 22px;
  color: rgb(10, 124, 142);
  transform: translateY(-30px);
  align-items: center;

  >span {
    position: absolute;
    margin-left: 20px;
  }
}
</style>
